from django.contrib import admin, messages
from django.utils.translation import gettext_lazy as _

from ceph.managers import RadosError
from .models import Vdisk, Quota, VdiskArchive


@admin.register(Quota)
class QuotaAdmin(admin.ModelAdmin):
    list_display_links = ('id',)
    list_display = ('id', 'name', 'group', 'cephpool', 'total', 'size_used', 'max_vdisk', 'get_stats_used', 'enable')
    search_fields = ['name']
    list_filter = ['group', 'cephpool']

    def get_stats_used(self, obj):
        s = obj.get_all_disk_size()
        if s >= 0:
            return s
        return 'get error'

    get_stats_used.short_description = _('实时统计的已使用容量(GB)')


@admin.register(Vdisk)
class VdiskAdmin(admin.ModelAdmin):
    list_display_links = ('uuid',)
    list_display = ('uuid', 'size', 'quota', 'vm', 'dev', 'enable', 'get_deleted', 'rbd_image_name', 'user', 'create_time',
                    'attach_time', 'remarks',)
    search_fields = ['uuid', 'vm', 'remarks']
    list_filter = ['quota', 'user', 'deleted']

    raw_id_fields = ('vm', 'user')

    def delete_queryset(self, request, queryset):
        """
        后台管理批量删除重写， 通过每个对象的delete()方法删除，同时会删除ceph rbd image
        """
        for obj in queryset:
            if not obj.is_mounted:    # 硬盘已挂载，不删除
                obj.do_delete()

    def get_deleted(self, obj):
        if obj.deleted:
            return '已删除'
        return '使用中'

    get_deleted.short_description = _('删除状态')


@admin.register(VdiskArchive)
class VdiskArchiveAdmin(admin.ModelAdmin):
    list_display_links = ('uuid',)
    list_display = ('uuid', 'size', 'quota', 'is_recover', 'rbd_image_name', 'user', 'create_time',
                    'attach_time', 'remarks',)
    search_fields = ['uuid', 'remarks']
    list_filter = ['quota', 'user']
    raw_id_fields = ('user',)
    actions = ['delete_rbd_image',]


    def delete_handle_obj(self, obj):
        """ """

        if obj.is_recover:  # 有rbd
            try:
                obj.do_delete(delete_data=True, delete_rbd=True)
            except Exception as e:
                raise e
            return

        try:
            obj.do_delete(delete_data=True, delete_rbd=False)
        except Exception as e:
            raise e

    def delete_handle_rbd(self, obj):

        if obj.is_recover:  # 有rbd
            try:
                obj.do_delete(delete_data=False, delete_rbd=True)

            except RadosError as e:
                obj.is_recover = False
                obj.save(update_fields=['is_recover'])
                raise e
            except Exception as e:
                raise e

    def delete_model(self, request, obj):

        try:
            self.delete_handle_obj(obj=obj)
        except Exception as e:
            msg = f'归档云硬盘删除失败，error: {str(e)}'
            self.message_user(request=request, message=msg, level=messages.ERROR)
            return

        msg = f'归档云硬盘删除成功'
        self.message_user(request=request, message=msg, level=messages.ERROR)

    def delete_queryset(self, request, queryset):
        """
        后台管理批量删除重写， 通过每个对象的delete()方法删除，同时会删除ceph rbd image
        """
        success_count = 0
        failed_count = 0
        for obj in queryset:
            try:
                # obj.do_delete(delete_data=delete_data)
                self.delete_handle_obj(obj=obj)
            except Exception as e:
                failed_count += 1
                msg = f'归档云硬盘删除成功：{success_count}个，失败{failed_count}个，error: {str(e)}'
                self.message_user(request=request, message=msg, level=messages.ERROR)
                return

            success_count += 1

        msg = f'归档云硬盘删除成功, 已删除：{success_count}个'
        self.message_user(request=request, message=msg, level=messages.SUCCESS)

        # self.delete_rbd_image(request, queryset)

    # def has_delete_permission(self, request, obj=None):
    #     return False

    def delete_rbd_image(self, request, queryset):
        """ 删除 rbd 镜像硬盘镜像"""
        success_count = 0
        failed_count = 0
        for obj in queryset:
            try:
                # obj.do_delete(delete_data=delete_data)
                self.delete_handle_rbd(obj=obj)
            except Exception as e:
                failed_count += 1
                msg = f'已删除rbd：{success_count}个，失败{failed_count}个，error: {str(e)}'
                self.message_user(request=request, message=msg, level=messages.ERROR)
                return

            success_count += 1

        msg = f'RBD删除成功, 已删除：{success_count}个'
        self.message_user(request=request, message=msg, level=messages.SUCCESS)

    delete_rbd_image.short_description = _('删除rbd')


    def get_actions(self, request):
        actions = super().get_actions(request)
        # 重命名删除操作
        if 'delete_selected' in actions:
            action = actions['delete_selected']
            action[0].short_description = '删除归档云硬盘'  # 修改提示文本

        return actions
